<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
           protected $fillable = [
               'name',
               'username',
               'email',
               'phone',
               'password',
               'avatar',
               'nickname',
               'signature',
               'bio',
               'exp',
               'followers_count',
               'following_count',
               'is_admin',
           ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
           protected $casts = [
               'email_verified_at' => 'datetime',
               'password' => 'hashed',
               'exp' => 'integer',
               'followers_count' => 'integer',
               'following_count' => 'integer',
               'is_admin' => 'boolean',
           ];

    /**
     * 获取用户等级（基于经验值计算）
     */
    public function getLevelAttribute(): int
    {
        // 简化版等级计算：每100经验值升一级
        return floor($this->exp / 100) + 1;
    }

    /**
     * 判断是否为全局管理员
     */
    public function isAdmin(): bool
    {
        return $this->is_admin === true;
    }

    /**
     * 用户创建的贴吧（作为吧主）
     */
    public function ownedBars()
    {
        return $this->hasMany(Bar::class, 'owner_id');
    }

    /**
     * 用户加入的贴吧（通过 bar_members 表）
     */
    public function joinedBars()
    {
        return $this->belongsToMany(Bar::class, 'bar_members')
            ->withPivot('role', 'joined_at')
            ->withTimestamps();
    }

    /**
     * 用户在贴吧中的成员关系
     */
    public function barMemberships()
    {
        return $this->hasMany(BarMember::class);
    }

    /**
     * 用户发布的帖子
     */
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    /**
     * 用户点赞的帖子
     */
    public function likedPosts()
    {
        return $this->belongsToMany(Post::class, 'post_likes')
            ->withTimestamps();
    }

    /**
     * 用户收藏的帖子
     */
    public function favoritedPosts()
    {
        return $this->belongsToMany(Post::class, 'favorites')
            ->withTimestamps();
    }

    /**
     * 用户的点赞记录
     */
    public function postLikes()
    {
        return $this->hasMany(PostLike::class);
    }

    /**
     * 用户的收藏记录
     */
    public function favorites()
    {
        return $this->hasMany(Favorite::class);
    }

    /**
     * 用户发布的回复
     */
    public function replies()
    {
        return $this->hasMany(Reply::class);
    }

    /**
     * 用户点赞的回复
     */
    public function likedReplies()
    {
        return $this->belongsToMany(Reply::class, 'reply_likes')
            ->withTimestamps();
    }

    /**
     * 用户的回复点赞记录
     */
    public function replyLikes()
    {
        return $this->hasMany(ReplyLike::class);
    }

    /**
     * 用户关注的用户（我关注的人）
     */
    public function followings()
    {
        return $this->belongsToMany(User::class, 'follows', 'follower_id', 'following_id')
            ->withTimestamps();
    }

    /**
     * 关注我的用户（粉丝）
     */
    public function followers()
    {
        return $this->belongsToMany(User::class, 'follows', 'following_id', 'follower_id')
            ->withTimestamps();
    }

    /**
     * 判断是否关注了指定用户
     */
    public function isFollowing(User $user): bool
    {
        return $this->followings()->where('following_id', $user->id)->exists();
    }

    /**
     * 判断指定用户是否关注了我
     */
    public function isFollowedBy(User $user): bool
    {
        return $this->followers()->where('follower_id', $user->id)->exists();
    }

    /**
     * Get the route key for the model.
     */
    public function getRouteKeyName()
    {
        return 'username';
    }

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($user) {
            // 如果没有 username，从 name 或 nickname 生成
            if (empty($user->username)) {
                $user->username = static::generateUsername($user->name ?? $user->nickname ?? 'user');
            }
        });
    }

    /**
     * 生成 username（使用拼音转换）
     */
    protected static function generateUsername(string $name): string
    {
        $pinyin = new \Overtrue\Pinyin\Pinyin();
        // 使用 permalink 方法，自动转换为拼音并用连字符分隔
        $baseUsername = $pinyin->permalink($name, '-');
        
        // 如果转为空（纯特殊字符），使用随机字符串
        if (empty($baseUsername)) {
            $baseUsername = 'user-' . Str::random(8);
        }
        
        // 移除连字符，限制长度
        $baseUsername = str_replace('-', '', $baseUsername);
        $baseUsername = Str::limit($baseUsername, 30, '');
        
        // 确保唯一性
        $username = $baseUsername;
        $counter = 1;
        while (static::where('username', $username)->exists()) {
            $username = $baseUsername . $counter;
            $counter++;
        }
        
        return $username;
    }
}
